
from utils.MyHashEncryptor import MyHashEncryptor as hash
import time,random


###slug 生成，加入请求体，自动保存
async def update_slug(body,model):
    if 'slug' in model._meta.fields:
        slug = hash.myencryped('md5',str(body) + str(int(time.time() * 1000000)) + str(random.randint(100,999)))
        body.update(slug=slug)
        return True
    return False

# ###summary 处理，自动截取文章前150个字
# async def summary_handler(body,model,create,obj_id=None):
#     if 'summary' not in body or 'summary' not in model._meta.fields:
#         return False
#     new_summary = body.get('summary')
#     new_body_150 = body.get('body')[:150]
#     if create:
#         old_body_150, old_summary = '', getattr(setting, 'DEFAULT_SUMMARY','')
#     else:
#         # print(await model.filter(id=obj_id).values('body'))
#         old_body_values= await model.filter(id=obj_id).values('body')
#         old_body_150 = old_body_values[0].get('body')[:150]
#         old_summary_values = await model.filter(id=obj_id).values('summary')
#         old_summary = old_summary_values[0].get('summary')
#     if (create and new_summary == '') \
#             or (not create and old_body_150 == old_summary \
#                 and new_body_150 != old_summary \
#                 or new_summary == ''):
#         body.update(summary=new_body_150)
#         return True
#     return False

#获取当前登录用户 加入文章中
async def update_author(body,model,user_id):
    if 'author_id' in model._meta.fields:
        body.update(author_id=user_id)
        return True
    return False


#去掉某字段,不显示
async def takeout_field(resource_response,field):
    if resource_response.get('fields').get(field):
        resource_response.get('fields').pop(field)
        return True
    return False

#限制用户，除了超管，只能选择自己
async def select_author(resource_response,fields,user):
    if not user.is_superuser:
        try:
            authors = resource_response.get(fields).get('author_id').get('options')
            resource_response[fields]['author_id']['options'] = []
            for author in authors:
                if author.get('value') == user.pk:
                    resource_response[fields]['author_id'].update(options = [author])
                    break
        except AttributeError:
            pass
        return True
    return False
